package com.xixing.weixin.domain;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import flexjson.JSONDeserializer;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class Weixin {

    public static final String TEXT = "text";
    private String toUserName;
    private String fromUserName;
    private Long createTime;

    // text,image,location,link,event.
    private String msgType;
    // text
    private String content;
    // image
    private String picUrl;
    // location
    private Double locationX;
    private Double locationY;
    private Double scale;
    private String label;
    // link
    private String title;
    private String description;
    private String url;


    private String msgId;

    public static Weixin fromXml(String xml) {
        String normalXml = normalize(xml);
        XStream xstream = new XStream();
        xstream.alias("xml", Weixin.class);
        return (Weixin)xstream.fromXML(normalXml);
    }






    // <To...> -> to..., </To...> -> </to...>
    protected static String normalize(String xml) {
        StringBuffer result = new StringBuffer();

        Pattern pattern = Pattern.compile("(<[A-Z])|(</[A-Z])");
        Matcher m = pattern.matcher(xml);

        while(m.find())
            m.appendReplacement(result, m.group().toLowerCase());

        m.appendTail(result);


        return result.toString();
    }


}
